<template>
  <div class="check-request-page">
    <!-- 标题与统计 -->
    <div class="header-row">
      <h1 class="page-title">检查申请</h1>
      <div class="stat">共 <b>{{ filteredList.length }}</b> 条</div>
    </div>

    <!-- 查询条件 -->
    <el-card class="filter-card" shadow="hover">
      <el-row :gutter="16" class="row-flex">
        <el-col :xs="24" :sm="8" :md="6">
          <el-input v-model="keyword" placeholder="按检查信息/备注搜索" clearable @keyup.enter="loadData" @clear="loadData">
            <template #append>
              <el-button type="primary" :icon="Search" @click="loadData" />
            </template>
          </el-input>
        </el-col>
        <el-col :xs="24" :sm="8" :md="6">
          <el-select v-model="projectType" placeholder="医技项目类型" clearable @change="loadData" style="width:100%">
            <el-option label="影像" value="img" />
            <el-option label="超声" value="us" />
            <el-option label="内镜" value="scope" />
            <el-option label="心电" value="ecg" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="8" :md="6">
          <el-select v-model="stateFilter" placeholder="状态过滤" clearable style="width:100%">
            <el-option label="已开立" value="已开立" />
            <el-option label="已缴费" value="已缴费" />
            <el-option label="已退费" value="已退费" />
            <el-option label="已作废" value="已作废" />
          </el-select>
        </el-col>
      </el-row>
    </el-card>

    <!-- 列表 -->
    <el-card class="list-card" shadow="hover">
      <el-table :data="pagedList" stripe :loading="loading" empty-text="暂无数据" style="width:100%">
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column prop="registerId" label="挂号ID" width="90" align="center" />
        <el-table-column prop="patientName" label="姓名" min-width="100" align="center" />
        <el-table-column prop="checkInfo" label="检查信息" min-width="160" show-overflow-tooltip />
        <el-table-column prop="checkState" label="状态" width="110" align="center">
          <template #default="{ row }">
            <el-tag :type="tagType(row.checkState)" effect="dark" size="small">{{ row.checkState || '未知' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="checkRemark" label="备注" min-width="140" show-overflow-tooltip />
        <el-table-column label="操作" width="340" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="showDetail(row)">查看详情</el-button>
            <el-button size="small" type="danger" plain :disabled="row.checkState==='已作废'" @click="cancel(row)">取消检查</el-button>
            <el-button size="small" type="primary" plain :disabled="!canCall(row)" @click="callPatient(row)">叫号</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager-wrapper" v-if="filteredList.length > pageSize">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :page-size="pageSize"
          :current-page="pageNum"
          :total="filteredList.length"
          @current-change="(p)=>{pageNum=p}"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="检查申请详情" width="640px" destroy-on-close>
      <el-descriptions :column="2" border size="small">
        <el-descriptions-item label="ID">{{ detail.id }}</el-descriptions-item>
        <el-descriptions-item label="挂号ID">{{ detail.registerId }}</el-descriptions-item>
        <el-descriptions-item label="医技项目ID">{{ detail.medicalTechnologyId }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ detail.checkState }}</el-descriptions-item>
        <el-descriptions-item label="检查信息" :span="2">{{ detail.checkInfo }}</el-descriptions-item>
        <el-descriptions-item label="检查部位" :span="2">{{ detail.checkPosition }}</el-descriptions-item>
        <el-descriptions-item label="检查结果" :span="2">{{ detail.checkResult }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.checkRemark }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatTime(detail.creationTime) }}</el-descriptions-item>
        <el-descriptions-item label="检查时间">{{ formatTime(detail.checkTime) }}</el-descriptions-item>
        <el-descriptions-item label="检查医生ID">{{ detail.checkEmployeeId }}</el-descriptions-item>
        <el-descriptions-item label="结果录入医生ID">{{ detail.inputcheckEmployeeId }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible=false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { fetchAll, fetchByCondition, fetchDetail, cancelRequest } from '@/api/checkRequest'

const router = useRouter()

// 查询条件
const keyword = ref('')
const projectType = ref('') // 医技项目类别（示例占位，真实需后端提供字段）
const stateFilter = ref('')

// 数据
const rawList = ref([])
const loading = ref(false)

// 分页
const pageNum = ref(1)
const pageSize = 10

// 详情
const detailVisible = ref(false)
const detail = ref({})

// 过滤逻辑（若后端增加条件接口，可直接调用 fetchByCondition）
const filteredList = computed(()=>{
  return rawList.value
    // 排除已出结果记录（交给“结果管理”模块展示）
    .filter(item => item.checkState !== '已出结果')
    .filter(item => {
      const kw = keyword.value.trim()
      const passKw = !kw || (item.checkInfo && item.checkInfo.includes(kw)) || (item.checkRemark && item.checkRemark.includes(kw)) || (item.patientName && item.patientName.includes(kw))
      const passType = !projectType.value || matchProjectType(item)
      const passState = !stateFilter.value || item.checkState === stateFilter.value
      return passKw && passType && passState
    })
})

const pagedList = computed(()=>{
  const start = (pageNum.value-1)*pageSize
  return filteredList.value.slice(start,start+pageSize)
})

function matchProjectType(item){
  // 暂无项目类型字段：可按 medicalTechnologyId 做简单映射
  if(!projectType.value) return true
  const id = item.medicalTechnologyId
  if(projectType.value==='img') return [1,2,3,4].includes(id)
  if(projectType.value==='us') return [5,6,7].includes(id)
  if(projectType.value==='scope') return [8,9].includes(id)
  if(projectType.value==='ecg') return [10,11].includes(id)
  return true
}

async function loadData(){
  loading.value = true
  try {
    // 后端暂无专门关键词+类型查询，这里直接取全部再前端过滤
    const res = await fetchAll()
    rawList.value = res.data || []
    pageNum.value = 1
  } catch (e){
    ElMessage.error(e.message || '加载失败')
  } finally {
    loading.value = false
  }
}

async function showDetail(row){
  try {
    const res = await fetchDetail(row.id)
    detail.value = res.data || {}
    detailVisible.value = true
  } catch(e){
    ElMessage.error(e.message || '获取详情失败')
  }
}

function formatTime(t){
  if(!t) return '-'
  const d = new Date(t)
  const pad = n=> n.toString().padStart(2,'0')
  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}

async function cancel(row){
  ElMessageBox.confirm(`确认将该检查(ID=${row.id})作废?`,`提示`,{type:'warning'})
    .then(async ()=>{
      try {
        await cancelRequest(row.id)
        ElMessage.success('已作废')
        loadData()
      } catch(e){
        ElMessage.error(e.message || '操作失败')
      }
    })
    .catch(()=>{})
}

function tagType(state){
  if(!state) return ''
  if(state.includes('作废')||state.includes('退')) return 'danger'
  if(state.includes('出结果')) return 'success'
  if(state.includes('执行')) return 'warning'
  if(state.includes('缴费')) return 'info'
  return ''
}

function callPatient(row){
  if(!canCall(row)) return
  // 存储当前患者检查申请到 sessionStorage 供录入页面使用
  sessionStorage.setItem('current_check_request', JSON.stringify(row))
  router.push('/check/patient')
}

function canCall(row){
  if(!row) return false
  // 禁止已作废、检查中、已出结果、已退费状态再次叫号，仅允许 "已缴费" 或 "已开立" （可按业务再调）
  const forbidden = ['已作废','检查中','已出结果','已退费']
  return row.checkState && !forbidden.includes(row.checkState)
}

watch([keyword, projectType, stateFilter],()=>{
  pageNum.value = 1
})

onMounted(()=>{
  loadData()
})
</script>

<style scoped>
.check-request-page { padding: 12px; }
.header-row { display:flex; align-items:center; gap:24px; margin-bottom:10px; }
.page-title { font-size:24px; font-weight:600; margin:0; letter-spacing:.5px; }
.stat { font-size:14px; color:#606266; }
.stat b { color:#409eff; }
.filter-card { border-radius:14px; margin-bottom:14px; }
.list-card { border-radius:14px; }
.pager-wrapper { display:flex; justify-content:flex-end; margin-top:12px; }
.el-table { --el-table-border-color:#ebeef5; }
</style>
